package com.gitee.deeround.jdbchelper.resultSetExtractors;

import com.gitee.deeround.jdbchelper.out.DataColumn;
import com.gitee.deeround.jdbchelper.out.DataTable;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DataTableResultSetExtractor extends BaseResultSetExtractor implements ResultSetExtractor<DataTable> {

    private String tableName;

    public DataTableResultSetExtractor(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public DataTable extractData(ResultSet rs) throws SQLException, DataAccessException {
        //ResultSet转DataTable
        ResultSetMetaData md = rs.getMetaData();

        //生成rows
        List<Object[]> rows = new ArrayList<>();
        int columnCount = md.getColumnCount();
        while (rs.next()) {
            Object[] rowData = new Object[columnCount];
            for (int j = 0; j < columnCount; j++) {
                rowData[j] = resolveDataValue(rs.getObject((j + 1)));
            }
            rows.add(rowData);
        }
        //生成columns
        List<DataColumn> columns = new ArrayList<>();
        for (int j = 0; j < columnCount; j++) {
            columns.add(new DataColumn(resolveColumnName(md.getColumnLabel(j + 1)), resolveDataType(md.getColumnType((j + 1)))));
        }
        //生成dataTable
        DataTable dt = new DataTable(tableName, rows);
        dt.setColumns(columns);

        return dt;
    }
}
